packages <- (c("tidyverse" , "stargazer" , "interflex" , "multiwayvcov" , "lmtest" , "broom" , "ggpubr" , "systemfit" , "car" , "lavaan" ,
               "mycor" , "psych" , "ggExtra" , "sjPlot" , "sjmisc" , "ggeffects" , "jtools" , "cowplot", "modelsummary", "here", "ggrepel", "haven",
               "PerformanceAnalytics", "polycor"))


installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}

# Packages loading
invisible(lapply(packages, library, character.only = TRUE))


#set graph parameters
theme_set(theme_bw())
theme_update(text = element_text(size=12),
             panel.grid.major = element_blank(),
             panel.grid.minor = element_blank(),
             strip.background = element_blank(),
             panel.background = element_blank()
)



## Custom Functions

#Custom function for reverse coding variables
flip <- function(x){
  minimum <- min(x, na.rm = T)
  maximum <- max(x, na.rm = T)
  
  (((x - maximum) * -1 ) + minimum)
}

#Custom function for 0-1 coding variables
zero1 <-  function(x) {
  (x - min(x, na.rm = TRUE))/diff(range(x, na.rm = TRUE))
}


#Custom Function for creating basic plots in study 8
plot_fun <- function(df, x, y, text, ...) {
  
  dat <- df %>%
    filter({{x}} != "NA")
  
  a <- sum_stat <- dat %>%
    group_by({{x}}) %>%
    summarise(
      mean = mean({{y}}, na.rm = TRUE),
      sd = sd({{y}}, na.rm = TRUE),
      n = n(),
      se = sd / sqrt(n),
      low_ci = mean-2*se,
      high_ci = mean+2*se
    )
  
  b <-   ggplot(dat, aes(x={{x}}, y={{y}})) + 
    geom_jitter(color = "grey",
                width = .01,
                height = .01) + 
    geom_linerange(data = sum_stat,
                   aes(x = {{x}}, 
                       ymin = low_ci, 
                       ymax = high_ci),
                   color = "Black", 
                   size = 1.8,
                   inherit.aes = F) +
    geom_point(data = sum_stat,
               aes(x = {{x}}, y = mean),
               size = 3.3, color = "Black") +
    coord_flip() +
    xlab("") +
    ggtitle(text)
  
  
  out <- list(a,b)
  
  return(out)
}
